package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.service.AdUserService;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.model.admin.adminDto.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author 石头
 * @description 针对表【ad_user(管理员用户信息表)】的数据库操作Service实现
 * @createDate 2022-06-24 09:13:32
 */
@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * 用户登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult adminLogin(AdUserDto dto) {
        log.info("平台管理登录已经执行");
        String name = dto.getName();
        String password = dto.getPassword();
        // 校验账号或者密码
        if (StringUtils.isBlank(name) || StringUtils.isBlank(password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 根据账号查询用户信息
        LambdaQueryWrapper<AdUser> queryWrapper = Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name);
        AdUser adUser = this.getOne(queryWrapper);
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 用户存在，校验密码
        String apUserPassword = adUser.getPassword();
        String salt = adUser.getSalt();
        String cryptPassword = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        // 密码错误返回错误提示
        if (!StringUtils.equals(cryptPassword, apUserPassword)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 生成token
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));

        // 信息脱敏,封装返回数据
        adUser.setSalt("");
        adUser.setPassword("");
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("user", adUser);
        resultMap.put("token", token);
        return ResponseResult.okResult(resultMap);
    }
}




